package com.bittech.springboot.smallfileserver.controller;

import com.bittech.springboot.smallfileserver.domain.File;
import com.bittech.springboot.smallfileserver.service.FileService;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.Optional;

/**
 * Author: secondriver
 * Created: 2018/8/25
 */
@Controller
@RequestMapping(value = "/view")
public class FileViewController {
    
    @Autowired
    private FileService fileService;
    
    
    /**
     * 在线显示文件
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Object> serveFileOnline(@PathVariable String id) {
        Optional<File> file = fileService.getFileById(id);
        return file.<ResponseEntity<Object>>map(f -> ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + f.getName() + "\"")
                .header(HttpHeaders.CONTENT_TYPE, f.getContentType())
                .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(f.getSize()))
                .header(HttpHeaders.CONNECTION, "close")
                .body(f.getContent().getData()))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount"));
        
    }
    
    
    /**
     * Web 上传
     *
     * @param file
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(),
                    new Binary(file.getBytes()));
            f.setMd5(DigestUtils.md5DigestAsHex(file.getInputStream()));
            fileService.saveFile(f);
        } catch (IOException ex) {
            ex.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "Your " + file.getOriginalFilename() + " is wrong!");
            return "redirect:/";
        }
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");
        return "redirect:/";
    }
    
}
